<template>
  <div class="foodList">
    <section class="foodList">
      <el-table
        :data="limits"
        style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="食品名称">
                <span>{{ props.row.specfoods[0].name }}</span>
              </el-form-item>
              <el-form-item label="餐馆名称">
                <span>{{ props.row.restaurant_id }}</span>
              </el-form-item>
              <el-form-item label="食品ID">
                <span>{{ props.row.specfoods[0].food_id }}</span>
              </el-form-item>
              <el-form-item label="餐馆ID">
                <span>{{ props.row.cate[0].name }}</span>
              </el-form-item>
              <el-form-item label="食品介绍">
                <span>{{ props.row.description }}</span>
              </el-form-item>
              <el-form-item label="餐馆地址">
                <span>{{ props.row.specfoods[0].restaurant_id  }}</span>
              </el-form-item>
              <el-form-item label="食品评分">
                <span>{{ props.row.rating }}</span>
              </el-form-item>
              <el-form-item label="食品分类">
                <span>{{ props.row.category_id }}</span>
              </el-form-item>
              <el-form-item label="月销量">
                <span>{{ props.row.specfoods[0].stock }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="食品名称" prop="specfoods[0].name"></el-table-column>
        <el-table-column label="食品介绍" prop="description"></el-table-column>
        <el-table-column label="评分" prop="rating"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>

            <el-button
              size="mini"
              type="danger"
              @click="handleDelete1(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </section>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="PageSize"
        layout="total,  prev, pager, next"
        :total="totalCount">
      </el-pagination>
    </div>
    <el-dialog
      title="修改食品信息"
      :visible.sync="dialogVisible"
      width="48%"
      :before-close="handleClose1">
      <el-form ref="form" :model="form" size="mini" label-width="80px">
        <el-form-item label="食品名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="食品介绍">
          <el-input v-model="form.description  "></el-input>
        </el-form-item>
        <el-form-item label="食品分类">
          <el-select v-model="form.attributes" placeholder="请选择店铺分类">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="食品图片">
          <el-upload
            style=" border: 1px dashed #d9d9d9;width: 90px ;border-radius: 6px;cursor: pointer;position: relative;overflow: hidden;"
            class="avatar-uploader"
            action="http://localhost:3000/statis/addimg/food"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.image_path" :src="form.image_path" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-table
          :data="form.attrs"
          style="width: 100%"
          :header-cell-style="{background:'#eef1f6',color:'#606266',textAlign:'center'}">
          <el-table-column
            prop="specs"
            label="规格">
          </el-table-column>
          <el-table-column
            prop="packing_fee"
            label="包装费">
          </el-table-column>
          <el-table-column
            prop="price"
            label="价格">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: center">
          <el-button type="primary" @click="add" size="mini" style="margin-top:8px">添加规格</el-button>
        </div>
        <div style="text-align: right">
          <el-button type="primary" @click="onSubmit" size="mini" style="margin-left: 13px;margin-top: 12px">确 定</el-button>
          <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog title="添加规格" :visible.sync="dialogFormVisible">
      <el-form :rules="specsFormrules" ref="specsFormrules" size="small" :model="specsForm">
        <el-form-item label="规格"  label-width="100px" prop="specs">
          <el-input v-model="specsForm.specs" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="包装费" label-width="100px">
          <el-input-number v-model="specsForm.packing_fee" :min="0" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="价格" label-width="100px">
          <el-input-number v-model="specsForm.price" :min="0" :max="10000"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addspecs('specsFormrules')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
  // import data from '../../assets/data'
  import {allFood, getFoodCategory, updateFood, deleteFood} from '../api/getData'
  import {baseImgUrl} from '../config/env'
  export default {
    name: 'foodlist',
    data() {
      return {
        img:'',
        item_id:0,
        // category_id:0,
        old_category:0,
        restaurant_id:0,
        options:[],
        specsFormrules: {
          specs: [
            { required: true, message: '请输入规格', trigger: 'blur' },
          ],
        },
        specsForm: {
          specs: '',
          packing_fee: 0,
          price: 20,
        },
        dialogFormVisible:false,
        imageUrl:'',
        limits:[],
        offset:0,
        dialogVisible: false,
        tableData: [],
        totalCount:0,//显示总条数
        currentPage:1,//显示当前页数
        PageSize:12,//每页显示的条数
        getUserData:[],
        form: {
          name: '',
          attributes:'',
          description: '',
          image_path:'',
          attrs:[]
        },
      }
    },
    created(){
      this.initData()
    },
    methods:{
      // async allFood(){
      //
      // },
      async handleDelete1(index,row){
        console.log(row)
        var res = await deleteFood({params:{category_id:row.category_id,item_id:row.item_id},credentials:true})
        if(!res.body.status){
          this.$message({
            type:'error',
            message:res.body.message + "删除失败"
          })
        }else{
          this.$message({
            type:'success',
            message:"删除成功"
          })
          this.getUser()
        }
      },
      async getType(restaurant_id) {
        var res = await getFoodCategory({ params: { restaurant_id: restaurant_id } })
        // console.log(res.body.result)
        try{
          // console.log("1")
          this.options = res.body.result.map((item) => {
            console.log(item)
            return {
              label: item.name,
              value: item.id
            }
          })
          console.log(this.options)
        }catch (e) {
          console.log(e)
        }

      },
      handleDelete(index){
        this.form.attrs.splice(index, 1);
      },
      addspecs(formName){
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            // console.log()
            this.form.attrs.push({ ...this.specsForm})
            this.dialogFormVisible = false
          }else{
            this.$message({
              type:'error',
              message:"请输入规格"
            })
          }
        })
      },
      handleAvatarSuccess (res, file) { // 和上传图片相关
        this.img = res.filename;
        this.form.image_path = URL.createObjectURL(file.raw); // 和上传图片相关
      },
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'image/jpeg' || 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      handleClose1(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      async initData(){
        try {
          // const userData={status:1,count:data.length}
          // if(userData.status==1){
          //     this.totalCount=userData.count
          // }
          this.getUser();//展示首页面
        } catch (error) {
          console.log("数据获取错误");
        }
      },
      async CountData(obj){
        const Users=[]
        for(let count=0;count<obj.PageSize;count++){
          Users[count]=this.getUserData[count]
        }
        return Users;
      },
      async getUser(){
        var res = await allFood({params:{offset:this.offset,limit:this.PageSize}})
        this.limits = res.body.result
        this.totalCount = res.body.count
        const returnUserData=this.CountData({
          currentPage:this.currentPage,
          PageSize:this.PageSize
        })
        //  console.log(returnUserData);
        returnUserData.then(res=>{
          this.tableData=[]
          res.forEach((item) => {
            // const Data=[]
            // Data.id=item.id,
            // Data.date=item.date,
            // Data.name=item.name,
            // Data.address=item.address
            // this.tableData.push(Data)
          });
        })
      },
      add(){
        this.dialogFormVisible = true
        console.log("tianjia")
      },
      async onSubmit() {
        // console.log('submit!');
        // this.form.image_path = this.img
        console.log(this.form.attributes)
        // if(this.form.attributes instanceof String){
        if(typeof this.form.attributes === 'string'){
          // console.log(this.options[0])
          this.form.attributes = this.old_category
        }
        // }
        // console.log(this.options)
        var res = await updateFood({params:{
            ...this.form,
            category_id:this.form.attributes,
            restaurant_id:this.restaurant_id,
            item_id:this.item_id,
            image_path:this.img,
            old_category:this.old_category
          }
        })
        if(res.body.status){
          await this.getUser();
          this.dialogVisible = false;
          this.$message({
            type:'success',
            message:'修改成功'
          })
        }else{
          this.$message({
            type:'error',
            message:'系统异常'
          })
        }

      },
      handleEdit(index, row) {
        try{
          this.restaurant_id = row.restaurant_id
          // this.category_id = row.category_id
          this.old_category = row.category_id,
            this.dialogVisible = true
          this.form.name = row.name;
          this.form.description = row.description;
          this.form.attributes = row.category[0].name;
          this.form.image_path = baseImgUrl + '/food/' + row.image_path;
          this.form.attrs = row.attrs
          this.item_id = row.item_id
          this.img = row.image_path
          this.getType(row.restaurant_id)
        }catch (e) {
          this.$message({
            type:'error',
            message:'数据出错'
          })
        }

        // console.log(index, row.category[0]);
        // this.dialogVisible = true
      },
      handleSizeChange(val){//每页条数改变时触发
        // this.PageSize=val
        // this.tableData=data.slice((this.currentPage-1)*this.PageSize,this.currentPage*this.PageSize)
      },
      handleCurrentChange(val){
        // this.currentPage=val
        this.offset = (val - 1) * this.PageSize
        this.getUser();
        // this.tableData=data.slice((this.currentPage-1)*this.PageSize,this.currentPage*this.PageSize)
      },
    },
  }
</script>

<style lang="less" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #000!important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
  }
  .avatar {
    width: 90px;
    height: 90px;
    display: block;
  }
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
